package com.bestcem.xm.member.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 对象与JSON转换
 * @date 2021-08-17
 */
@Slf4j
@Component
public class ObjectMapperTemplate {
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 尝试将Java对象转换为JSON字符串
     *
     * @param obj
     * @return
     */
    public String tryConvertToJSONStr(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("try convert to jsonStr failed, obj: {}", obj, e);
        }
        return null;
    }

    /**
     * 尝试将JSON字符串转换为Java对象
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T tryConvertToJavaObject(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (Exception e) {
            log.error("try convert to java object failed, jsonStr: {}, clazz: {}", jsonStr, clazz, e);
        }
        return null;
    }

    /**
     * 尝试将JSON字符串转换为Java列表
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> tryConvertToJavaList(String jsonStr, Class<T> clazz) {
        if (StringUtils.isBlank(jsonStr) || clazz == null) {
            return null;
        }

        try {
            return objectMapper.readerForListOf(clazz).readValue(jsonStr);
        } catch (Exception e) {
            log.error("try convert to java list failed, jsonStr: {}, clazz: {}", jsonStr, clazz, e);
        }
        return null;
    }
}
